package com.manor.main.dialog;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.manor.common.dialog.AbsDialogFragment;
import com.manor.common.utils.AudioRecorderEx;
import com.manor.common.utils.FilePathUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.WordUtil;
import com.manor.im.utils.VoiceMediaPlayerUtil;
import com.manor.main.R;
import com.manor.main.activity.EditUserInfoActivity;

import java.io.File;

/**
 * 用户语音的录制

 * @version 1.0

 * @date 2020/4/11  18:54
 */

public class UserVoiceDialogFragment extends AbsDialogFragment implements View.OnClickListener {
    private static final int MAX_RECORD_TIME = 5;
    private static final int VOICE_PLAYING = 1;//录音中
    private static final int VOICE_RECORD = 2;//点击录音,待开始
    public static final int VOICE_REPLAY = 3;//可播放

    public static final int MIN_VOICE_TIME = 2;

    private int mCurVoiceType = VOICE_RECORD;

    private boolean isRecordEnd = false;



    private View mBtnConfirm;
    private TextView mTvRecordTime;
    private ProgressBar mProgressBar;
    private ImageView mIvRecord;
    private boolean mIsRecording;//是否在录制
    private boolean mIsPlaying;//是否在试听
    private AudioRecorderEx mAudioRecorderEx;
    private VoiceMediaPlayerUtil mVoiceMediaPlayerUtil;
    private File mVoiceFile;
    private int mCurTime;
    private int mCurPlayTime;//试听时间
    private String mRecordStr;
    private String mPauseStr;
    private Drawable mDrawable;
    private Drawable mDrawable2;
//    private AnimationDrawable mAnimationDrawable;
    private boolean mIsNeedMerge;
    private TextView tvText;//上方描述文字
    private LinearLayout llBottom;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==VOICE_RECORD){
                if (mCurTime == MAX_RECORD_TIME) {
                    if (llBottom!=null){
                        llBottom.setVisibility(View.VISIBLE);
                    }
                    mCurVoiceType = VOICE_REPLAY;
                    setImgStatus();
                    recordAndPause();
                } else {
                    mCurTime++;
                    mProgressBar.setProgress(mCurTime);
                    mTvRecordTime.setText(mCurTime + "s");
                    tvText.setText(mCurTime + "s");
                    mHandler.sendEmptyMessageDelayed(VOICE_RECORD, 1000);
                }
            }else if (msg.what==VOICE_PLAYING){
                mCurPlayTime++;
                if (mCurPlayTime>mCurTime){
                    mCurPlayTime=mCurTime;
                }
                mProgressBar.setProgress(mCurPlayTime);
                mHandler.sendEmptyMessageDelayed(VOICE_PLAYING, 1000);
            }

        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.dialog_voice_record_user;
    }

    @Override
    protected int getDialogStyle() {
        return com.manor.dynamic.R.style.dialog_sd;
    }

    @Override
    protected boolean canCancel() {
        return true;
    }

    @Override
    protected void setWindowAttributes(Window window) {
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM;
        window.setAttributes(params);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mBtnConfirm = findViewById(R.id.btn_confirm);
        mTvRecordTime = (TextView) findViewById(R.id.time);
        mProgressBar = (ProgressBar) findViewById(R.id.progress);
        mIvRecord = (ImageView) findViewById(R.id.btn_record);
        tvText = (TextView) findViewById(R.id.tv_text);
        llBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        mBtnConfirm.setOnClickListener(this);
        //mBtnPlay.setOnClickListener(this);
        mIvRecord.setOnClickListener(this);
        findViewById(R.id.btn_cancel).setOnClickListener(this);
        mProgressBar.setMax(MAX_RECORD_TIME);
        mRecordStr = WordUtil.getString(R.string.click_record);
        mPauseStr = WordUtil.getString(R.string.click_pause);
        mDrawable = mContext.getDrawable(R.mipmap.voice_play);
        mDrawable2 = mContext.getDrawable(R.mipmap.voice_pause);
        mAudioRecorderEx = AudioRecorderEx.getInstance(mContext);
//        mAnimationDrawable= (AnimationDrawable) mIvRecord.getDrawable();
    }

    private void recordAndPause() {
        mCurPlayTime=0;
        if (!mIsRecording) {
            mAudioRecorderEx.setOutputFile(FilePathUtil.makeFilePath(mContext, AudioRecorderEx.AUDIO_DIR_PATH, System.currentTimeMillis() + AudioRecorderEx.AUDIO_SUFFIX_MP3));
            mAudioRecorderEx.prepare();
            mAudioRecorderEx.start();
            mIsRecording = true;
            mIsNeedMerge = true;
            if (mHandler != null) {
                mHandler.sendEmptyMessageDelayed(VOICE_RECORD, 1000);
            }
        } else {
            if (mCurTime< MIN_VOICE_TIME){
                ToastUtil.show(WordUtil.getString(R.string.im_record_audio_too_short));
                if (!isRecordEnd) {
                    mCurVoiceType = VOICE_PLAYING;
                    setImgStatus();
                }
                return;
            }
            if (mHandler != null) {
                mHandler.removeMessages(VOICE_RECORD);
            }
            mAudioRecorderEx.stop();
            mAudioRecorderEx.reset();
            mIsRecording = false;
            isRecordEnd = true;
        }
    }

    private void playVoice() {
        if (mIsPlaying) {
            mIsPlaying = false;
            if (mVoiceMediaPlayerUtil != null) {
                mVoiceMediaPlayerUtil.pausePlay();
            }
            mHandler.removeMessages(VOICE_PLAYING);
        } else {
            if (mIsNeedMerge){
                mVoiceFile = mAudioRecorderEx.mergeAudioFile();
                mIsNeedMerge=false;
            }
            if (mVoiceMediaPlayerUtil == null) {
                mVoiceMediaPlayerUtil = new VoiceMediaPlayerUtil(mContext);
                mVoiceMediaPlayerUtil.setActionListener(new VoiceMediaPlayerUtil.ActionListener() {
                    @Override
                    public void onPlayEnd() {
                        mIsPlaying = false;
                        mCurVoiceType = VOICE_REPLAY;
                        setImgStatus();
                        mHandler.removeMessages(VOICE_PLAYING);
                        mCurPlayTime=0;
                    }
                });
            }
            mIsPlaying = true;
            if (mVoiceMediaPlayerUtil.isPaused()) {
                mVoiceMediaPlayerUtil.resumePlay();
            } else {
                mVoiceMediaPlayerUtil.startPlay(mVoiceFile.getAbsolutePath());
            }
            mHandler.sendEmptyMessageDelayed(VOICE_PLAYING, 1000);
        }
    }

    private void confirm(){
        if (mIsNeedMerge){
            mVoiceFile = mAudioRecorderEx.mergeAudioFile();
            mIsNeedMerge=false;
        }
        ((EditUserInfoActivity)mContext).addVoiceInfo(mVoiceFile,mCurTime);
        dismiss();
    }

    private void del() {
        mCurTime=0;
        mAudioRecorderEx.reset();
        mAudioRecorderEx.clearData();
        mAudioRecorderEx.deleteMixRecorderFile(mVoiceFile);
        mProgressBar.setProgress(0);
//        mAnimationDrawable.stop();
//        mTvRecord.setText(mRecordStr);
        mTvRecordTime.setText(mCurTime + "s");
        tvText.setText(mCurTime + "s");
//        if (mBtnConfirm!=null){
//            mBtnConfirm.setVisibility(View.GONE);
//        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_cancel) {
            dismiss();
        } else if (i == R.id.btn_confirm) {
            confirm();
        }else if (i == R.id.btn_record) {
            statusForVoice();
        }
    }


    private void setImgStatus(){
        switch (mCurVoiceType) {
            case VOICE_PLAYING://录音中
                mIvRecord.setBackgroundResource(R.mipmap.ic_voice_stop);
                break;
            case VOICE_RECORD://点击录音,待开始
                mIvRecord.setBackgroundResource(R.mipmap.ic_voice_start);
                break;
            case VOICE_REPLAY://录音结束,可播放
                mIvRecord.setBackgroundResource(R.mipmap.ic_voice_play);
                break;
        }
    }

    private void statusForVoice(){
        switch (mCurVoiceType) {
            case VOICE_PLAYING://录音中
                llBottom.setVisibility(View.VISIBLE);
                mCurVoiceType = VOICE_REPLAY;
                if (isRecordEnd)
                    playVoice();
                else
                    recordAndPause();
                break;
            case VOICE_RECORD://点击录音,待开始
                mCurVoiceType = VOICE_PLAYING;
                recordAndPause();
                break;
            case VOICE_REPLAY://可播放
                mCurVoiceType = VOICE_PLAYING;
                playVoice();
                break;
        }
        setImgStatus();
    }


    @Override
    public void dismiss() {
        super.dismiss();
        if (mVoiceMediaPlayerUtil != null) {
            mVoiceMediaPlayerUtil.destroy();
        }
        if (mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }
        mHandler=null;
    }
}
